package unicall.unicom.uniwell;

import java.io.File; import java.io.InputStream; 
import java.io.RandomAccessFile; 
import java.net.HttpURLConnection; 
import java.net.URL;

import android.os.Bundle; 
import android.os.Handler;
import android.os.Message; 
import android.widget.Toast;

public class DownLoadThread extends Thread {

public static int size=0;

private int j;//线程的ID
private File file;//本地文件
private URL url;//网络资源路径
private int block;//下载的块
private Handler myhandler;//负责和线程进行交互


public DownLoadThread(int j, File file, URL url, int block,Handler myhandler) {

    this.j=j;
    this.file=file;
    this.url=url;
    this.block=block;
    this.myhandler=myhandler;

}

public void run() {

    try{
        HttpURLConnection con = (HttpURLConnection)url.openConnection();
        con.setReadTimeout(5000);
        con.setRequestMethod("GET");
        //计算开始点和结束点
        int start = (j*block);
        int end = (j+1)*block-1;

        RandomAccessFile af = new RandomAccessFile(file,"rwd");
        af.seek(start);//寻找写入的位置
        //设置请求的头文件--由于是多线程下载--所以要设置区域下载大小的头文件bytes=1-11
        con.setRequestProperty("Range", "bytes="+start+"-"+end);
        //根据返回的状态嘛判断是否成功
        if(con.getResponseCode() == 206 ){//下载链接成功的状态吗为 206
            InputStream in = con.getInputStream();
            byte[] buf = new byte[1024];
            int len=0;
            while((len=in.read(buf))!=-1){
                //计算目前总的下载量
                DownLoadThread.getSize(len,this.myhandler);
                af.write(buf,0,len);
            }
            af.close();
            in.close();
            System.out.println("第"+j+"线程完成下载");
        }else{
            System.out.println("第"+j+"线程无法完成下载");
        }

    }catch(Exception e){
        e.printStackTrace();
    }


}

private synchronized  static void getSize(int len,Handler myhandler) {

    DownLoadThread.size+=len;
    Message msg = new Message();
    Bundle b = new Bundle();
    b.putInt("size", DownLoadThread.size);
    msg.setData(b);
    msg.what=1;
    myhandler.sendMessage(msg);

}
}